package com.detrum.wifidevice;

import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import com.detrum.wifidevice.bean.WifiInfoBean;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by abc on 2018/1/29.
 */

public class WifiObject implements WifiInterface{
    private List<ScanResult> destList,list_wifi;
    private String previousSSID;
    private int previous;
    public void ScanWifi(WifiManager mWifiManager, WifiSacnCall wifiSacnCall){
        destList = new ArrayList<>();//可连接的或之前连接过的设备wifi
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
        mWifiManager.startScan();//开始扫描
        list_wifi = mWifiManager.getScanResults();
        if (list_wifi != null && list_wifi.size() != 0) {
            for (int i = 0; i < list_wifi.size(); i++) {
                if (list_wifi.get(i).SSID.contains(WifiFinal.Head)) {
                    destList.add(list_wifi.get(i));
                }
            }
            WifiInfoBean wifiInfoBean = new WifiInfoBean();
            List<WifiInfoBean.DataBean> beanList = new ArrayList<>();
            if (destList != null && destList.size() != 0) {
                int size = destList.size();
                for (int i = 0; i < size; i++) {
                    WifiInfoBean.DataBean bean = new WifiInfoBean().new DataBean();
                    bean.setSSID(destList.get(i).SSID);
                    bean.setRssi(WifiManager.calculateSignalLevel(destList.get(i).level, 100));
                    SupplicantState state = mWifiManager.getConnectionInfo().getSupplicantState();
                    previousSSID = mWifiManager.getConnectionInfo().getSSID();//获取当前已经连接的设备
                    mWifiManager.getConnectionInfo().getBSSID();
                    previous = mWifiManager.getConnectionInfo().getNetworkId();
                    if (previousSSID.equals("\"" + destList.get(i).SSID + "\"")) {
                        if(state==SupplicantState.COMPLETED){
                            bean.setConnect(true);
                        }else{
                            bean.setConnect(false);
                        }
                    } else {
                        bean.setConnect(false);
                    }
                    beanList.add(bean);
                }
            } else {
                // 附近没有指定设备，找不到能匹配成功的WiFi
                List<WifiConfiguration> configList = mWifiManager.getConfiguredNetworks();
                int size = configList.size();
                for (int i = 0; i < size; i++) {
                    Log.e("第" + i + "个" + "configList", configList.get(i).SSID);
                    if (configList.get(i).SSID.contains(WifiFinal.Head)) {
                        WifiInfoBean.DataBean bean = new WifiInfoBean().new DataBean();
                        String SSID = configList.get(i).SSID.replace("\"","");
                        bean.setSSID(SSID);
                        bean.setRssi(0);
                        bean.setConnect(false);
                        bean.setPrevious(previous);
                        beanList.add(bean);
                    }
                }

            }
            if (beanList != null && beanList.size() != 0) {
                wifiInfoBean.setBeanList(beanList);
                Gson gson = new Gson();
                final String json = gson.toJson(wifiInfoBean);
                Log.e("json", json);
                wifiSacnCall.listResult(json);
            } else {
                wifiSacnCall.scanFail();
            }
        } else {
            //附近没有wifi
            wifiSacnCall.scanFail();
        }
    }

    @Override
    public void ConnectWifi(WifiManager mWifiManager, String SSID) {
        int id;
        if (isConfigExist(mWifiManager,SSID) == null) {
            id = mWifiManager.addNetwork(createWifiInfo(SSID, WifiFinal.PassWord));
        } else {
            id = isConfigExist(mWifiManager,SSID).networkId;

        }
        mWifiManager.enableNetwork(id, true);
    }

    @Override
    public void GetData() {

    }

    @Override
    public void SendOrder() {

    }

    /**
     * 判断系统是否保存过该WIFI网络
     *
     * @param ssid
     * @return
     */
    private WifiConfiguration isConfigExist(WifiManager mWifiManager, String ssid) {
        if (mWifiManager.isWifiEnabled()) {
            List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
            if (null != wifiConfigurations) {
                for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                    if (("\"" + ssid + "\"").equals(wifiConfiguration.SSID)) {
                        return wifiConfiguration;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据WIFI名称SSID，创建WifiConfiguration对象
     *
     * @param SSID
     * @param password
     * @return
     */
    public WifiConfiguration createWifiInfo(String SSID, String password) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        try {
            // 分为三种情况：1没有密码2用wpa加密
            int type = TextUtils.isEmpty(password) ? 1 : 2;
            if (1 == type) {
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            } else if (2 == type) {
                config.preSharedKey = "\"" + password + "\"";
                config.hiddenSSID = true;
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                config.status = WifiConfiguration.Status.ENABLED;
            }
        } catch (Exception e) {
            return null;
        }
        return config;
    }
}
